package nc.files.ct.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

public class IOStreamOperator {

	public static void close(InputStream in, OutputStream out) {
		if (in != null) {
			try {
				in.close();
			} catch (IOException exception) {
				exception.printStackTrace();
			}
		}

		if (out != null) {
			try {
				out.close();
			} catch (IOException exception) {
				exception.printStackTrace();
			}
		}
	}

	public static void close(InputStreamReader reader, OutputStreamWriter writer) {
		if (reader != null) {
			try {
				reader.close();
			} catch (IOException exception) {
				exception.printStackTrace();
			}
		}

		if (writer != null) {
			try {
				writer.close();
			} catch (IOException exception) {
				exception.printStackTrace();
			}
		}
	}

	public static void copy(InputStream in, OutputStream out) {
		BufferedInputStream bin = new BufferedInputStream(in);
		BufferedOutputStream bout = new BufferedOutputStream(out);
		byte[] row = new byte[4096];

		try {
			for (int count = bin.read(row); count > 0; count = bin.read(row)) {
				bout.write(row, 0, count);
			}

			bout.flush();
		} catch (IOException exception) {
			exception.printStackTrace();
		}
	}

	public static byte[] readBytes(InputStream in) {
		ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
		copy(in, out);
		return out.toByteArray();
	}
}
